﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace TiebaSpider.Core
{
    class ForumAnalysiser
    {
        private Crawler crawler;
        private bool captureSign;

        public Beans.HistoryForum RequestForum { get; set; }
        public event EventHandler<ForumAnalysiserEventArgs> AnalysisComplete;

        public ForumAnalysiser()
        {
            crawler = new Crawler();
            crawler.CrawlerEvent += OnForumCapture;
            captureSign = false;
        }

        public ForumAnalysiser(Beans.HistoryForum forum)
            : this()
        {
            RequestForum = forum;
        }

        public void OnForumCapture(object sender, CrawlerEventArgs e)
        {
            captureSign = true;
        }

        public async void RequestThreads(int pages)
        {
            Beans.ForumInformation forumContent = new Beans.ForumInformation();
            crawler.TargetURL = string.Format(Beans.AnalysisExpressions.ForumPagingUrl, RequestForum.EncodeName, (pages - 1) * 50);
            captureSign = false;
            string forumPageContent = await crawler.GetStringContent();
            while (!captureSign) { }
            if (!forumPageContent.Equals(string.Empty))
            {
                Match totalPageMatch = Regex.Match(forumPageContent, Beans.AnalysisExpressions.ForumPagingDetection);
                if (totalPageMatch.Success)
                {
                    forumContent.TotalPages = long.Parse(totalPageMatch.Groups[1].Value) / 50;
                }
                else
                {
                    forumContent.TotalPages = 1L;
                }
                MatchCollection threadMatches = Regex.Matches(forumPageContent, Beans.AnalysisExpressions.ThreadCaptureFormForum);
                foreach (Match match in threadMatches)
                {
                    Beans.ForumThread threadUnit = new Beans.ForumThread();
                    threadUnit.TID = match.Groups[1].Value;
                    threadUnit.Name = match.Groups[2].Value;
                    forumContent.ThreadCache.Add(threadUnit);
                }
            }
            if (AnalysisComplete != null)
                AnalysisComplete(this, new ForumAnalysiserEventArgs(forumContent));
        }
    }

    public class ForumAnalysiserEventArgs : EventArgs
    {
        public Beans.ForumInformation ForumInfo { get; private set; }

        public ForumAnalysiserEventArgs(Beans.ForumInformation info)
        {
            ForumInfo = info;
        }
    }
}
